package com.lzymall.controller.backend;

import com.lzymall.common.Const;
import com.lzymall.common.ServiceResponse;
import com.lzymall.pojo.User;
import com.lzymall.service.IUserService;
import com.lzymall.util.CookieUtil;
import com.lzymall.util.JsonUtil;
import com.lzymall.util.RedisPoolUtil;
import com.lzymall.util.RedisShardedPoolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author: lizhenyao
 * @Desciption:
 */
@Controller
@RequestMapping("manage/user")
public class UserManageController {

    @Autowired
    private IUserService iUserService;

    @RequestMapping(value = "login.do", method = RequestMethod.POST)
    @ResponseBody
    public ServiceResponse<User> login(String username, String password, HttpServletResponse httpServletResponse, HttpSession session){
        ServiceResponse<User> response = iUserService.login(username, password);
        if (response.isSuccess()){
            User user = response.getData();
            if (user.getRole() == Const.Role.ROLE_ADMIN){
//                session.setAttribute(Const.CURRENT_USER, user);

                CookieUtil.writeLoginToken(httpServletResponse, session.getId());
                RedisShardedPoolUtil.setEx(session.getId(), JsonUtil.obj2String(user),Const.RedisCacheExtime.REDIS_CHACHE_EXTIME);
                return response;
            }else {
                return ServiceResponse.createByErrorMessage("不是管理员,无法登陆");
            }
        }
        return response;
    }
}
